package com.hsmpay.mobile.action.base;

import com.hsmpay.common.action.BaseAction;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.JSONStringBuilder;
import com.hsmpay.common.util.MD5;
import com.hsmpay.common.util.jiami.Des3;
import com.hsmpay.mobile.pojo.system.ErrorCode;
import com.hsmpay.mobile.pojo.terminal.TerminalPrivileges;
import com.hsmpay.mobile.service.system.ErrorCodeService;
import com.hsmpay.mobile.service.terminal.TerminalPrivilegesService;
import com.hsmpay.mobile.service.user.UserService;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 手机端 base action
 *
 * @author 颜铃璋
 * @date 2012-12-14
 */
@Controller("mobileBaseAction")
public class MobileBaseAction extends BaseAction {
    private static Logger log = Logger.getLogger(MobileBaseAction.class);
    private static final long serialVersionUID = 1L;

    @Resource(name = "userService")
    protected UserService<User, Long> userService;
    @Resource(name = "terminalPrivilegesService")
    protected TerminalPrivilegesService<TerminalPrivileges, Long> terminalPrivilegesService;
    @Resource(name = "errorCodeService")
    protected ErrorCodeService<ErrorCode, Long> errorCodeService;//错误代码
    public Integer start;//分页 开始索引
    public Integer stop;//分页 结束索引

    public final String FC_DATA = "fc_data";
    public final String FC_DES3_Key = "fc_des3_key";
    protected JSONObject jsonParam = null;

    protected Long terminalTypeId;//终端类型（1简易型 2）
    protected Long roleId;
    protected Integer clientType;//客户端类型：1网站 2安卓 3iphone 4ipad
    protected Long userId;
    protected String functionKey;

    /**
     * 检查功能 是否有效
     * check Privileges Is Valid
     *
     * @param functionKey
     * @return
     */
    public boolean checkPIV(String functionKey) throws Exception {
        TerminalPrivileges terminalPrivileges = terminalPrivilegesService.checkPrivilegesIsValid(functionKey);
        if (null == terminalPrivileges || terminalPrivileges.getStatus().intValue() == 1) {
            return true;
        }else if(terminalPrivileges.getStatus().intValue() == 2){
            log.warn("检查终端功能时, 该功能暂时停止使用！");
            sendAppErrorMsg("6002");
        }else if(terminalPrivileges.getStatus().intValue() == 3){
            log.warn("系统日切中,请稍候...");
            sendAppErrorMsg("6110");
        }
        return false;
    }

    /**
     * 检查功能 是否有效
     * check Privileges Is Valid
     *
     * @param functionKey
     * @return
     */
    public boolean checkWeChartPIV(String functionKey) throws Exception {
        TerminalPrivileges terminalPrivileges = terminalPrivilegesService.checkPrivilegesIsValid(functionKey);
        if (null == terminalPrivileges || terminalPrivileges.getStatus().intValue() == 1) {
            return true;
        }else if(terminalPrivileges.getStatus().intValue() == 2){
            log.warn("检查终端功能时, 该功能暂时停止使用！");
            sendWeChatErrorMsg("6002");
        }else if(terminalPrivileges.getStatus().intValue() == 3){
            log.warn("系统日切中,请稍候...");
            sendWeChatErrorMsg("6110");
        }
        return false;
    }

    /**
     * @param status   1 成功 0 失败
     * @param str1     status==1 明文json数据 status==0 错误代码
     * @param str2     status==1 动态密钥 status==0 错误描述
     *                 正常响应格式：1|BASE64(3DES(报文))|BASE64(MD5(报文))
     *                 错误响应格式：0|错误码|BASE64(错误描述)
     * @return
     * @throws Exception
     */
    public String encryptAppMsg(int status, String str1, String str2) {
        StringBuilder sb = new StringBuilder();
        try {
            sb.append(status).append("|");
            if (1 == status) {//1|BASE64(3DES(报文))|BASE64(MD5(报文))
                String data = Des3.encode(str1, str2);
                sb.append(data).append("|");

                String md5 = MD5.mD5ofStr(data);//明文MD5值
                String md5Data = new String(Base64.encode(md5.getBytes("UTF-8")), "UTF-8");
                sb.append(md5Data);
            } else {
                sb.append(str1).append("|");

                String desc = new String(Base64.encode(str2.getBytes("UTF-8")), "UTF-8");
                sb.append(desc);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 返回Ajax响应字符串，将处理结果返回
     */
    public void sendAppMsg(String str1, String str2) {
        String message = encryptAppMsg(1, str1, str2);
        log.debug("-------------------响应String数据---------------------\n json=" + str1 + "\n\n 加密后数据=" + message + "\n----------------------------------------------");
        sendAppMsg(message);
    }

    /**
     * 返回App端 0|错误码|BASE64(错误描述)
     *
     * @param code
     * @param param 参数
     */
    public void sendAppErrorMsg(String code, String param) {
        String desc = "";
        try {
            ErrorCode ec = errorCodeService.getErrorCodeByCode(code);
            if (null == ec) {
                ec = errorCodeService.getErrorCodeByCode("9998");
                desc = ec.getDisplayDesc().replaceAll("\\$param", param);
                code = "9998";
            } else {
                desc = ec.getDisplayDesc().replaceAll("\\$param", param);
            }

            String message = encryptAppMsg(0, code, desc);
            log.debug("-------------------响应String数据---------------------\n code=" + code + "\n desc=" + desc + "\n\n 加密后数据=" + message + "\n----------------------------------------------");
            sendAppMsg(message);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 返回App端 0|错误码|BASE64(错误描述)
     *
     * @param code
     */
    public void sendAppErrorMsg(String code) {
        sendAppErrorMsg(code, "");
    }

    /**
     * 返回Ajax响应字符串，将处理结果返回
     *
     * @param obj  数据
     * @param str2 des3动态密钥
     */
    protected void sendAppMsg(Object obj, String str2) {
        String str = JSONStringBuilder.getAjaxString(obj);
//		str = str.replaceAll("\\\\", "");
        String message = encryptAppMsg(1, str, str2);
        log.debug("-------------------响应json数据---------------------\n json=" + str + "\n\n 加密后数据=" + message + "\n----------------------------------------------");
        sendAppMsg(message);
    }

    /**
     * 返回Ajax响应字符串，将处理结果返回
     *
     * @param obj 数据
     */
    public void sendAppMsg(Object obj) {
        String fc_des3_key = (String) getRequest().getAttribute(FC_DES3_Key);
        sendAppMsg(obj, fc_des3_key);
    }

    /**
     * 返回Ajax响应字符串，将处理结果返回
     *
     * @param list     查询数据
     */
    @SuppressWarnings("unchecked")
    protected void sendAppMsg(List list, String str2) {
        String str = JSONStringBuilder.getAjaxString(list);
        String message = encryptAppMsg(1, str, str2);
        log.debug("-------------------响应json数据---------------------\n json=" + str + "\n\n 加密后数据=" + message + "\n----------------------------------------------");
        sendAppMsg(message);
    }

    /**
     * 给App发送数据
     *
     * @param str
     */
    public void sendAppMsg(String str) {
        try {
            HttpServletResponse res = getResponse();
            res.setCharacterEncoding("UTF-8");
            res.setContentType("text/json");
            //getResponse().addHeader("Content-Length", str.getBytes("UTF-8").length+"");
            res.getWriter().print(str);

            //释放内存
            getRequest().removeAttribute(FC_DES3_Key);
            getRequest().removeAttribute(FC_DATA);
            jsonParam = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected String getJsonString(String key) {
        if (null == jsonParam)
            jsonParam = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        String result = jsonParam.containsKey(key) ? jsonParam.getString(key) : "";
        if (result.length() < 1000) {
            log.debug(key + " = " + result);
        }
        return result;
    }

    protected String getWechartString(String key) {
        return getRequest().getParameter(key);
    }

    /**
     * 向微信公众号客户端响应数据
     * @param resMsg
     */
    public void sendWeChatMsg(String resMsg) {
        try {
            HttpServletResponse res = getResponse();
            res.setCharacterEncoding("UTF-8");
            res.getWriter().print(resMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向微信公众号客户端响应数据
     * @param code
     * @param param
     */
    public void sendWeChatErrorMsg(String code, String param) {
        String desc = "";
        try {
            ErrorCode ec = errorCodeService.getErrorCodeByCode(code);
            if (null == ec) {
                ec = errorCodeService.getErrorCodeByCode("9998");
                desc = ec.getDisplayDesc().replaceAll("\\$param", param);
                code = "9998";
            } else {
                desc = ec.getDisplayDesc().replaceAll("\\$param", param);
            }
            JSONObject json = new JSONObject();
            json.put("code",code);
            json.put("msg",desc);
            sendThirdMsg(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向第三方响应错误信息
     * @param code
     * @param param
     */
    public void sendThirdErrorMsg(String code, String param) {
        try {
            JSONObject json = new JSONObject();
            json.put("code",code);
            json.put("message",param);
            sendThirdMsg(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向第三方响应数据库内错误码对应信息
     * @param code
     * @param param
     */
    public void sendThirdDBMsg(String code, String param) {
        String desc = "";
        try {
            ErrorCode ec = errorCodeService.getErrorCodeByCode(code);
            if (null == ec) {
                ec = errorCodeService.getErrorCodeByCode("9998");
                desc = ec.getDisplayDesc().replaceAll("\\$param", param);
                code = "9998";
            } else {
                desc = ec.getDisplayDesc().replaceAll("\\$param", param);
            }
            JSONObject json = new JSONObject();
            json.put("code",code);
            json.put("message",desc);
            sendThirdMsg(json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendThirdMsg(String resMsg) {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            getResponse().getOutputStream().write(resMsg.getBytes("UTF-8"));
            getResponse().flushBuffer();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向微信公众号客户端响应数据
     * @param code
     */
    public void sendWeChatErrorMsg(String code) {
        sendWeChatErrorMsg(code,"");
    }



    //---------------------set get start---------------------
    public void setStart(Integer start) {
        this.start = start;
    }

    public void setStop(Integer stop) {
        this.stop = stop;
    }
    //---------------------set get end-----------------------
}
